//
//  KCWorkTaiController.swift
//  MyKC
//
//  Created by yy on 2017/4/6.
//  Copyright © 2017年 com.yasuo. All rights reserved.
//

import UIKit
import CoreLocation
import SVProgressHUD

class KCWorkTaiController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //请求授权
        manager.requestWhenInUseAuthorization()
        manager.delegate = self
        manager.startUpdatingLocation()
        
        getSalesData()
        getSignMessage()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        manager.stopUpdatingLocation()
        manager.delegate = nil
    }
    
    lazy var tableView: UITableView = {
        let tb = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight), style: .plain)
        tb.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tb.tableFooterView = UIView()
        tb.delegate = self
        tb.dataSource = self
        return tb
    }()
    //到信息 的数组
    lazy var signInArray = [KCWorkTaiSignInfoModel]()
    //销量信息的模型
    lazy var saleDayModel = KCWorkTaiSaleInfoModel()
    //销量和缺货状态的模型-----
    lazy var saleStatusArray = [KCWorkTaiSaleStatusModel]()
    //位置管理器
    lazy var manager:CLLocationManager = CLLocationManager()
    //编码器
    lazy var geocoder:CLGeocoder = CLGeocoder()
    
    //定位经纬度
    lazy var location:String = ""
    //定位地址信息
    lazy var localAddress:String = ""
    
    lazy var storeId = ""
}

// MARK: -  设置界面基本信息
extension KCWorkTaiController {
    internal func setupUI() {
        navigationItem.title = "我的工作台"
        setupTableView()
    }
    private func setupTableView() {
        view.addSubview(tableView)
        //注册nib文件
        tableView.register(UINib(nibName: "KCSignInOutCell", bundle: nil), forCellReuseIdentifier: "KCSignInOutCellId")
        tableView.register(UINib(nibName: "KCSaleDayReportCell", bundle: nil), forCellReuseIdentifier: "KCSaleDayReportCellId")
        tableView.register(UINib(nibName: "KCDetailSaleCell", bundle: nil), forCellReuseIdentifier: "KCDetailSaleCellId")
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50
        tableView.backgroundColor = colorBack
    }
}

// MARK: -  tableView的代理方法
extension KCWorkTaiController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = getIdentifier(indexPath: indexPath)
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        setupCell(cell: cell, indexPath: indexPath)
        return cell
    }
    
    private func getIdentifier(indexPath:IndexPath) -> String {
        if indexPath.row == 0 {
            return "KCSignInOutCellId"
        }
        if indexPath.row == 1 {
            return "KCSaleDayReportCellId"
        }
        else {
            return "KCDetailSaleCellId"
        }
    }
    
    private func setupCell(cell:UITableViewCell,indexPath:IndexPath) {
        cell.selectionStyle = .none
        if indexPath.row == 0 {
            let cellSign = cell as! KCSignInOutCell
            cellSign.signArray = signInArray
            cellSign.delegate = self
        }
        else if indexPath.row == 1 {
            let cellSaleDay = cell as! KCSaleDayReportCell
            cellSaleDay.model = saleDayModel
        }
        else {
            let cellDetailSale = cell as! KCDetailSaleCell
            if saleStatusArray.count != 0 {
                cellDetailSale.indexPath = indexPath
                cellDetailSale.model = saleStatusArray[indexPath.row - 2]
            }
        }
    }
}

// MARK: -  签到cell的代理-----里面的签到按钮的点击事件
extension KCWorkTaiController:KCSignInOutCellDelegate {
    func signBtnClick(tag: NSInteger) {
        if isLocalEnable() == false {
            return
        }
        let dic = ["Location":location,"LocationAddress":localAddress]
        var urlString = ""
         //签到
        if tag == 10 {
            urlString = "/api/Attendance/OnDuty"
        }
         //签退
        else if tag == 20 {
            urlString = "/api/Attendance/OffDuty"
            if signInArray.count == 0 {
                SVProgressHUD.showError(withStatus: "请先进行上班签到")
                return
            }
        }
        KCNetworkManager.sharedTools.request(method: .POST, urlString: urlString, parameters: dic) {[weak self] (response, error) in
            if response != nil {
                SVProgressHUD.showSuccess(withStatus: "签到成功")
                //不需要延迟执行-----
//                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: nil)
                self?.getSignMessage()
            }
        }
    }
    
    
    
    
    
    // MARK: -  判断是否开启定位功能-----
    private func isLocalEnable() -> Bool {
        var isEnable = false
        if CLLocationManager.locationServicesEnabled() == true || CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            if location.characters.count == 0 || localAddress.characters.count == 0 {
                //定位失败了 说明
                SVProgressHUD.showError(withStatus: "定位失败")
            }else {
                isEnable = true
            }
        }
            //说明定位没有打开
        else {
            SVProgressHUD.showError(withStatus: "请打开定位设置")
        }
        return isEnable
    }
}

extension KCWorkTaiController:CLLocationManagerDelegate {
    //更新位置信息后调用  为了避免频繁调用可以设置一个距离
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locationL = locations.last else {
            return
        }
        let longitude = locationL.coordinate.longitude
        let latitude = locationL.coordinate.latitude
        location = "\(longitude)" + "," + "\(latitude)"
        geocoder.reverseGeocodeLocation(locationL) { (placeMarks, error) in
            if placeMarks?.count == 0 || error != nil{
                return
            }
            for placeMark in placeMarks! {
//                self.localAddress = placeMark.locality!
                self.localAddress = placeMark.name!
            }
        }
    }
}


// MARK: -  获取网络数据
extension KCWorkTaiController {
    internal func getSalesData() {
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/Task/GetPromoterSalesData", parameters: nil) {[weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSDictionary else {
                return
            }
            self?.saleDayModel.yy_modelSet(with: responseContent as! [AnyHashable : Any])
            self?.storeId = self?.saleDayModel.StoreId ?? ""
            self?.getLessStatus(storeId: (self?.storeId)!)
        }
    }
    
    internal func getLessStatus(storeId: String) {
        let stidXLTB = "CtrlSalesVolume_" + storeId
        let stidQHSB = "CtrlOutOfStock_" + storeId
        let stid = stidXLTB + ";" + stidQHSB
        let dic = ["CtrlIds":stid]
        KCNetworkManager.sharedTools.request(method: .POST, urlString: "/api/CtrlMark/Query", parameters: dic) {[weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSArray else {
                return
            }
            self?.saleStatusArray = NSArray.yy_modelArray(with: KCWorkTaiSaleStatusModel.self, json: responseContent) as? [KCWorkTaiSaleStatusModel] ?? [KCWorkTaiSaleStatusModel]()
            self?.tableView.reloadData()
        }
    }
    
    internal func getSignMessage() {
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/Attendance/Today", parameters: nil) {[weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSArray else {
                return
            }
            self?.signInArray = NSArray.yy_modelArray(with: KCWorkTaiSignInfoModel.self, json: responseContent) as? [KCWorkTaiSignInfoModel] ?? [KCWorkTaiSignInfoModel]()
            self?.tableView.reloadData()
        }
    }
}


